﻿using MediatR;
using ProduceBasicData.Api.Application.Command.RBAC.Permission;
using ProduceBasicData.Domain.RBAC;
using ProduceBasicData.ErrorCode;
using ProduceBasicData.Infrastructure.Interface;

namespace ProduceBasicData.Api.Application.Handler.RBAC.Permission
{
    /// <summary>
    /// 检查权限是否有子权限的处理程序
    /// </summary>
    public class HasChildPermissionsHandler : IRequestHandler<HasChildPermissionCommand, ApiResult<bool>>
    {
        private readonly IBaseRespository<PermissionModel> _permissionRepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="permissionRepository"></param>
        public HasChildPermissionsHandler(IBaseRespository<PermissionModel> permissionRepository)
        {
            _permissionRepository = permissionRepository;
        }

        /// <summary>
        /// 处理检查权限是否有子权限的请求
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ApiResult<bool>> Handle(HasChildPermissionCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<bool>();

            try
            {
                // 获取所有未删除的权限
                var permissions = await _permissionRepository.GetAllAsync();

                // 检查是否存在ParentId等于当前权限ID且未删除的权限
                bool hasChildren = permissions.Any(x =>
                    x.Isdel == false &&
                    x.ParentId == request.PermissionId);

                result.Data = hasChildren;
                result.Code = ApiEnum.Success;
                result.Msg = "查询成功";
            }
            catch (Exception ex)
            {
                // 记录日志（实际项目中应使用专门的日志组件）
                // logger.LogError(ex, "检查子权限异常");

                result.Code = ApiEnum.Failed;
                result.Msg = $"检查异常: {ex.Message}";
                result.Data = false;
            }

            return result;
        }
    }
}
